package dao;

import java.sql.*;
import java.util.*;

import model.Title;
import utils.DbUtils;

/**
 * 作业题目访问类
 */
public class TitleDao {
	/**
	 * 新增
	 */
	public int add(Title title) {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = DbUtils.getConnection();
			String sql = "insert into title(title_content,title_course,title_time)values(?,?,?)";
			ps = conn.prepareStatement(sql);
			ps.setString(1, title.getTitleContent());
			ps.setInt(2, title.getTitleCourse());
			ps.setString(1, title.getTitleTime());
			return ps.executeUpdate();
		} catch (SQLException e) {
			return 0;
		} finally {
			DbUtils.releaseConnection(null, ps, conn);
		}
	}

	/**
	 * 根据id删除
	 */
	public int deleteById(int titleId) {
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = DbUtils.getConnection();
			String sql = "delete from title where title_id=?";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, titleId);
			return ps.executeUpdate();
		} catch (SQLException e) {
			return 0;
		} finally {
			DbUtils.releaseConnection(null, ps, conn);
		}
	}

	/**
	 * 获取全部
	 */
	public List<Title> getTitles() {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		List<Title> titles = new ArrayList<Title>();
		try {
			conn = DbUtils.getConnection();
			String sql = "select * from title";
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				titles.add(makeOneTitle(rs));
			}
		} catch (SQLException e) {
		} finally {
			DbUtils.releaseConnection(rs, ps, conn);
		}
		return titles;
	}

	/**
	 * 获取一个
	 */
	public Title makeOneTitle(ResultSet rs) throws SQLException {
		Title title = new Title();
		title.setTitleId(rs.getInt("title_id"));
		title.setTitleContent(rs.getString("title_content"));
		title.setTitleCourse(rs.getInt("title_course"));
		title.setTitleTime(rs.getString("title_time"));
		return title;
	}

	/**
	 * 根据id修改其他信息
	 */
	public int update(Title title) {
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			conn = DbUtils.getConnection();
			String sql = "update title set title_content=?,title_course=?,title_time=? where title_id=? ";
			ps = conn.prepareStatement(sql);
			ps.setString(1, title.getTitleContent());
			ps.setInt(2, title.getTitleCourse());
			ps.setString(3, title.getTitleTime());
			ps.setInt(4, title.getTitleId());
			return ps.executeUpdate();
		} catch (SQLException e) {
			return 0;
		} finally {
			DbUtils.releaseConnection(rs, ps, conn);
		}
	}
}

